package project.Service.Impl;

import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import project.Mapper.ChatMapper;
import project.Pojo.Chat.AI.ChatRecord;
import project.Pojo.Chat.AI.DeepSeekRequest;
import project.Pojo.Chat.AI.DeepSeekResponse;
import project.Pojo.Chat.ChatRoom;
import project.Pojo.Chat.ChatRoomUser;
import project.Pojo.RequestJsonPojo.Message;
import project.Pojo.Result;
import project.Service.ChatService;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class ChatServiceImpl implements ChatService {
    @Autowired
    ChatMapper chatMapper;

    @Autowired
    OllamaChatModel ollama;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${deepseek.url}")
    private String apiurl;

    @Value("${deepseek.key}")
    private String apipasword;

    @Value("${spring.ai.ollama.chat.model}")
    private String model;
    @Override
    public Result<String> callAi(Message message) {
        DeepSeekRequest deepSeekRequest = new DeepSeekRequest();
        //构建请求体
        deepSeekRequest.setModel(model);
        List<DeepSeekRequest.Message> messages=new ArrayList<>();
        messages.add(new DeepSeekRequest.Message("" +
                "你是一名专业的心理咨询师，擅长认知行为疗法（CBT）。\n" +
                "请用温暖、共情的中文与用户交流，避免直接给出建议，\n" +
                "而是通过提问引导用户自我反思。语气要温和且非评判性。"
                ,"system"));
        messages.add(new DeepSeekRequest.Message(message.getMessage(),"user"));
        deepSeekRequest.setMessages(messages);

        //构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON); // 声明发送JSON数据
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization","Bearer "+apipasword);

        // 封装请求实体（头+体）
        HttpEntity<DeepSeekRequest> entity = new HttpEntity<>(deepSeekRequest, headers);

        //发送请求：
        ResponseEntity<DeepSeekResponse> response=restTemplate.postForEntity(
                apiurl,
                entity,
                DeepSeekResponse.class
        );
        //存入数据
        ChatRecord record=new ChatRecord();
        ChatRecord record1=new ChatRecord();
        //存储文字
        record.setMsgContent(response.getBody().getChoices().get(0).getMessage().getContent());
        record1.setMsgContent(message.getMessage());
        //存储用户id
        record.setUserId(message.getUsername());
        record1.setUserId(message.getUsername());
        //存储信息时间
        LocalDate currentDate = LocalDate.now();
        // 创建 DateTimeFormatter 对象，设置日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 格式化当前日期为字符串
        String formattedDate = currentDate.format(formatter);
        record.setMsgDate(java.sql.Date.valueOf(formattedDate));
        record1.setMsgDate(java.sql.Date.valueOf(formattedDate));
        //存储ai||用户的标识
        record.setMsgRole(1);
        record1.setMsgRole(0);
        insertAiRecord(record);
        insertAiRecord(record1);
        return new Result<>(200, "AI",record.getMsgContent() );
    }

    @Override
    public void insertAiRecord(ChatRecord chatRecord) {
        chatMapper.insertAiRecord(chatRecord);
    }

    @Override
    public List<ChatRecord> getRecordByUserId(String userId) {
        return chatMapper.getRecordByUserId(userId);
    }

    @Override
    public void insertRoom(String name, String admin) {
        chatMapper.insertRoom(name, admin);
    }

    @Override
    public int selectRoomId(String name) {
        return chatMapper.selectRoomId(name);
    }

    @Override
    public void insertRoomUser(String admin, int id) {
        chatMapper.insertRoomUser(admin, id);
    }

    @Override
    public void deleteRoom(int id) {
        chatMapper.deleteRoom(id);
    }

    @Override
    public List<ChatRoom> selectRoomById(int id) {
        return chatMapper.selectRoomById(id);
    }

    @Override
    public void deleteRoomUser(int roomId, String username) {
        chatMapper.deleteRoomUser(roomId, username);
    }

    @Override
    public ChatRoomUser selectRoomUserByRoomIdAndUsername(int roomId, String username) {
        return chatMapper.selectRoomUserByRoomIdAndUsername(roomId, username);
    }

}
